//
//  ILGRunloopModule.m
//  ILGDemo
//
//  Created by happy on 2020/5/8.
//  Copyright © 2020 Happy. All rights reserved.
//

#import "ILGRunloopModule.h"

@implementation ILGRunloopModule
{
    NSThread *_thread;
    BOOL _isStoped;
}

- (void)performTestMethod
{
    [self startTaskInNewThread];
}

- (void)startTaskInNewThread
{
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(taskAction) object:nil];
    [thread start];
    _thread = thread;
}

- (void)taskAction
{
    @autoreleasepool {
        NSRunLoop *currentLoop = [NSRunLoop currentRunLoop];
//        [currentLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];

//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            NSLog(@"%s, %@, \n %@", __func__, [NSThread currentThread], [NSRunLoop currentRunLoop]);
//        }];
        
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionForDisplayLink) userInfo:nil repeats:YES];
//        [currentLoop addTimer:timer forMode:NSDefaultRunLoopMode];
        
        CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(actionForDisplayLink)];
        displayLink.preferredFramesPerSecond = 1; //在子线程中设置没用，好像依然60帧/s
        [displayLink addToRunLoop:currentLoop forMode:NSDefaultRunLoopMode];

        [self setupObserverForCurrentRunloop];

//        NSLog(@"ILGRunLoop runMode before");
//        [currentLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//        NSLog(@"ILGRunLoop runMode after");

        while (!_isStoped) {
            NSLog(@"ILGRunLoop runMode before");
            [currentLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            NSLog(@"ILGRunLoop runMode after");
        }
    }
}

- (void)actionForDisplayLink
{
    NSLog(@"%s, %@", __func__, [NSThread currentThread]);
}

- (void)setupObserverForCurrentRunloop
{
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        switch (activity) {
            case kCFRunLoopEntry:
                NSLog(@"RunLoop进入 %@", [NSRunLoop currentRunLoop].currentMode);
                break;
            case kCFRunLoopBeforeTimers:
                NSLog(@"RunLoop要处理Timers了");
                break;
            case kCFRunLoopBeforeSources:
                NSLog(@"RunLoop要处理Sources了");
                break;
            case kCFRunLoopBeforeWaiting:
                NSLog(@"RunLoop要休息了");
                break;
            case kCFRunLoopAfterWaiting:
                NSLog(@"RunLoop醒来了");
                break;
            case kCFRunLoopExit:
                NSLog(@"RunLoop退出了");
                break;
                
            default:
                break;
        }
    });
    // 给RunLoop添加监听者
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopCommonModes);
    
//    // 2.子线程需要开启RunLoop
//    [[NSRunLoop currentRunLoop] run];
    CFRelease(observer);
}


- (void)stopRunloop
{
//    [self performSelector:@selector(_stopCurrentloop) onThread:_thread withObject:nil waitUntilDone:YES];
}

- (void)_stopCurrentloop
{
    _isStoped = YES;
    CFRunLoopStop([NSRunLoop currentRunLoop].getCFRunLoop);
}
    

- (void)performTask
{
    [self performSelector:@selector(printSomething) onThread:_thread withObject:nil waitUntilDone:NO];
}

- (void)printSomething
{
//    dispatch_async(dispatch_get_main_queue(), ^{
//        NSLog(@"%s, %@", __func__, [NSThread currentThread]);
//    });
    
    NSLog(@"%s, %@, \n %@", __func__, [NSThread currentThread], [NSRunLoop currentRunLoop]);
}

@end
